import { Component, ViewChild } from '@angular/core';
import { Platform, ToastController, Nav, IonicApp, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { RestService } from '../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';
declare var screen :any;
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any;
  backButtonPressed: boolean = false;
  @ViewChild('myNav') nav: Nav;

  constructor(public ionicApp: IonicApp,
    public platform: Platform,
    private statusBar: StatusBar,
    public toastCtrl: ToastController,
    private splashScreen: SplashScreen,
    private events: Events,
    private translate: TranslateService,
    private rest: RestService) {
    platform.ready().then(() => {
      screen.orientation.lock('portrait');
      this.translate.addLangs(['zh', 'en', 'tw']);
      this.translate.setDefaultLang('en');
      this.registerBackButtonAction();
      let language = this.rest.getLanguage();
      if (!language) {
        const browserLang = this.translate.getBrowserCultureLang();
        if (browserLang === 'zh-TW') {
          language = 'tw';
        } else if (browserLang.startsWith('en')) {
          language = 'en';
        } else {
          language = 'zh';
        }
        console.info('Use browser settings to set language: ' + browserLang);
        this.translate.use(language);
        this.rest.saveLanguage(language);
      } else {
        console.info('Use saved language: ' + language);
        this.translate.use(language);
      }

      if (!this.rest.doLoginFlag) {
        this.rootPage = TabsPage;
        this.appReady();
        return;
      }

      /*
          this.rootPage = TabsPage;
          this.appReady();
          */
      this.events.subscribe('token:failed', () => {
        this.rootPage = LoginPage;
      });

      const user = this.rest.getUser();
      if (user && user.username && user.role && user.password) {
        this.rest.getTokenFromServer({
          grant_type: 'password',
          username: user.username,
          password: user.password,
          client_id: 'webmobile',
        }, data => {
          const token = data['access_token'];
          this.rest.saveToken(token);
          const refreshToken = data['refresh_token'];
          this.rest.saveRefreshToken(refreshToken);
          this.rootPage = TabsPage;
          this.appReady();
        }, () => {
          this.rootPage = LoginPage;
          this.appReady();
        });
      } else {
        this.rootPage = LoginPage;
        this.appReady();
      }
    });
  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      let activePortal = this.ionicApp._modalPortal.getActive();
      if (activePortal) {
        activePortal.dismiss().catch(() => { });
        activePortal.onDidDismiss(() => { });
        return;
      }
      let activeVC = this.nav.getActive();
      let tabs = activeVC.instance.tabs;
      let activeNav = tabs.getSelected();
      return activeNav.canGoBack() ? activeNav.pop() : this.showExit();
    }, 1);
  }

  //Double click to quit
  showExit() {
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      this.toastCtrl.create({
        message: this.translate.get('pressAgaintoQuit')['value'],
        duration: 2000,
        position: 'middle'
      }).present();
      this.backButtonPressed = true;
      setTimeout(() => this.backButtonPressed = false, 2000);
    }
  }
  appReady() {
    this.statusBar.styleDefault();
    this.statusBar.overlaysWebView(false);
    this.splashScreen.hide();
  }
}
